package org.example.service.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.domain.Permission;
import org.example.domain.Users;
import org.example.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author beikbei
 * @version 1.0
 * @description: TODO
 * @date 2024/5/11 10:15
 */
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 构造查询条件
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username", username);
        // 2. 查询用户
        Users users = usersMapper.selectOne(wrapper);

        if (users == null) {
            return null;
        }
        // 3. 查询用户权限
        List<Permission> permissions = usersMapper.findPermissionByUsername(username);
        // 4. 将自定义权限集合转为Security的权限集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }
        // 5. 封装为UserDetails对象
        UserDetails userDetails = User
                .withUsername(users.getUserName())
                .password(users.getPassword())
                .authorities(grantedAuthorities)
                .build();
        // 6. 返回封装好的UserDetails对象
        return userDetails;
    }
}
